package com.hwl.service;

import com.hwl.dao.UserMapper;
import com.hwl.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

public class UserService {
    //获取mybatis工厂对象
    public SqlSession getSession() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatisConfig.xml");
        SqlSessionFactory sqlsessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlsessionFactory.openSession(true);
        return sqlSession;
    }
    //关流方法
    public void close() throws IOException {
        SqlSession session = getSession();
        session.close();
    }

    //添加方法
    public void insertuser() throws IOException {
        SqlSession session = getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = new User(1, "黄文龙", 18, "男");
        mapper.insertuser(user);
        close();

    }
    //查询方法
    public void selecttuser() throws IOException {
        SqlSession session = getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.selectuser(1);
        close();
    }
    //修改方法
    public void updateuser() throws IOException {
        SqlSession session = getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.updateuser("李永健",27,"男",1);
        close();
    }
    //删除方法
    public void deleteuser() throws IOException {
        SqlSession session = getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.deleteuser(1);
        close();
    }
}
